﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Telerik.WebControls;
using System.Collections.Generic;
using Runda.CMS.Common.Utility;  

namespace Runda.CMS.Portal.ContractManage
{
    public partial class ContractItemListPutView : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ContractID"] != null)
                {
                    ddlPutPaymentType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.PutPaymentType)));

                    txtContractID.Value = Request.QueryString["ContractID"];

                    InitContractInfo();
                    InitOthorIncome();
                    BindContractGift();
                    BindContractItem(string.Empty);
                }
            }
        }

        private void InitOthorIncome()
        {
            if (txtContractID.Value == "") return;
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractOthorIncomeExtendEntity entity = bll.Get<CtrtContractOthorIncomeExtendEntity>(new Guid(txtContractID.Value));
            if (entity != null)
            {
                radtxtMachinePeriod.Value = entity.MachinePeriod;
                radtxtMachinePerIncome.Value = (double)entity.MachinePerIncome;
                radtxtMachineTotalIncome.Value = (double)entity.MachineTotalIncome;
                if (entity.MachineDate != DateTime.MinValue)
                {
                    raddateMachineDate.SelectedDate = entity.MachineDate;
                }
                radtxtAlertDays.Value = (double)entity.MachineAlertDays;
                txtMachineRemark.Text = entity.MachineRemark;

                radtxtMaintainPeriod.Value = entity.MaintainPeriod;
                radtxtMaintainPerIncome.Value = (double)entity.MaintainPerIncome;
                radtxtMaintainTotalIncome.Value = (double)entity.MaintainTotalIncome;
                if (entity.MaintainDate != DateTime.MinValue)
                {
                    raddateMaintainDate.SelectedDate = entity.MaintainDate;
                }
                radtxtAlertDays.Value = (double)entity.MaintainAlertDays;
                txtMaintainRemark.Text = entity.MaintainRemark;

                radtxtRentPeriod.Value = entity.RentPeriod;
                radtxtRentPerIncome.Value = (double)entity.RentPerIncome;
                radtxtRentTotalIncome.Value = (double)entity.RentTotalIncome;
                if (entity.RentDate != DateTime.MinValue)
                {
                    raddateRentDate.SelectedDate = entity.RentDate;
                }
                radtxtAlertDays.Value = (double)entity.RentAlertDays;
                txtRentRemark.Text = entity.RentRemark;
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindContractItem(string.Empty);
        }

        protected void btnRefreshSubItem_Click(object sender, EventArgs e)
        {
            BindContractSubItem(string.Empty);
        }

        protected void btnRefreshGuaranty_Click(object sender, EventArgs e)
        {
            BindGuaranty();
        }

        private void BindContractItem(string OrderBy)
        {
            ContractBll bll = new ContractBll();
            DataTable dt = bll.GetContractItemTable(" and ParentID IS null and ContractID = '" + txtContractID.Value + "'", OrderBy);

            gridContractItems.DataSource = dt;
            gridContractItems.DataBind();
        }

        private void BindContractSubItem(string OrderBy)
        {
            ContractBll bll = new ContractBll();
            DataTable dt = bll.GetContractItemTable(" and ParentID = '" + txtItemID.Value + "'", OrderBy);

            gridSubItems.DataSource = dt;
            gridSubItems.DataBind();
        }

        private void BindGuaranty()
        {
            if (txtItemID.Value != string.Empty)
            {
                //gridGuaranty.DataSource = new CtrtItemGuarantyBll().GetAll<CtrtItemGuarantyEntity>(" and ItemID ='" + txtItemID.Value + "'");
                //gridGuaranty.DataBind();
            }
        }

        protected void gridContractItems_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;

            if (e.CommandName == "delete")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());
                ContractBll bll = new ContractBll();
                bll.DeleteContractItem(ItemID);
                BindContractItem(string.Empty);
                BindGuaranty();
            }

            if (e.CommandName == "save")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());

                TextBox txtCount = e.Item.FindControl("txtCount") as TextBox; //数量
                //TextBox txtPrice = e.Item.FindControl("txtPrice") as TextBox; //销售价
                TextBox txtGuaranteeYear = e.Item.FindControl("txtGuaranteeYear") as TextBox;//保修年份
                //TextBox txtGuaranteeVendor = e.Item.FindControl("txtGuaranteeVendor") as TextBox;//厂家保修年限
                TextBox txtRepairCost = e.Item.FindControl("txtRepairCost") as TextBox;//维修成本
                //TextBox txtLeasingRestrict = e.Item.FindControl("txtLeasingRestrict") as TextBox;//租赁年限
                //TextBox txtLeasingPrice = e.Item.FindControl("txtLeasingPrice") as TextBox;//租赁费
                TextBox txtPromiseRevenue = e.Item.FindControl("txtPromiseRevenue") as TextBox;//承诺耗材销售额
                TextBox txtPutPeriod = e.Item.FindControl("txtPutPeriod") as TextBox;

                decimal Count = 0;
                if (txtCount.Text.Trim() != string.Empty)
                {
                    decimal.TryParse(txtCount.Text.Trim(), out Count);
                }

                //decimal Price = 0;
                //if (txtPrice.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtPrice.Text.Trim(), out Price);
                //}

                int GuaranteeYear = 0;
                if (txtGuaranteeYear.Text.Trim() != string.Empty)
                {
                    int.TryParse(txtGuaranteeYear.Text.Trim(), out GuaranteeYear);
                }

                //int GuaranteeVendor = 0;
                //if (txtGuaranteeVendor.Text.Trim() != string.Empty)
                //{
                //    int.TryParse(txtGuaranteeVendor.Text.Trim(), out GuaranteeVendor);
                //}

                //decimal RepairCost = 0;
                //if (txtRepairCost.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtRepairCost.Text.Trim(), out RepairCost);
                //}

                //int LeasingRestrict = 0;
                //if (txtLeasingRestrict.Text.Trim() != string.Empty)
                //{
                //    int.TryParse(txtLeasingRestrict.Text.Trim(), out LeasingRestrict);
                //}

                //decimal LeasingPrice = 0;
                //if (txtLeasingPrice.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtLeasingPrice.Text.Trim(), out LeasingPrice);
                //}

                decimal PromiseRevenue = 0;
                if (txtPromiseRevenue.Text.Trim() != string.Empty)
                {
                    decimal.TryParse(txtPromiseRevenue.Text.Trim(), out PromiseRevenue);
                }

                int PutPeriod = 0;
                if (txtPutPeriod.Text.Trim() != string.Empty)
                {
                    int.TryParse(txtPutPeriod.Text.Trim(), out PutPeriod);
                }
                CtrtContractItemBll bll = new CtrtContractItemBll();
                CtrtContractItemEntity entity = bll.Get<CtrtContractItemEntity>(ItemID);
                entity.Count = Count;
                //entity.Price = Price;
                //entity.TotalPrice = Count * Price;
                entity.GuaranteeYear = GuaranteeYear;
                //entity.GuaranteeVendor = GuaranteeVendor;
                //entity.RepairCost = RepairCost;
                //entity.LeasingRestrict = LeasingRestrict;
                //entity.LeasingPrice = LeasingPrice;
                entity.PromiseRevenue = PromiseRevenue;
                entity.PutPeriod = PutPeriod;

                bll.Update(entity);
                BindContractItem(string.Empty);
            }

        }

        protected void gridContractItems_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = " Order by " + e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            BindContractItem(OrderBy);
        }

        protected void gridContractItems_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                TextBox txtCount = e.Item.FindControl("txtCount") as TextBox;
                DataRowView dv = e.Item.DataItem as DataRowView;

                if (dv["Type"] != DBNull.Value && dv["Type"] != null && Convert.ToInt32(dv["Type"].ToString()) == 2)
                {
                    txtCount.Enabled = false;
                }

            }
        }

        protected void gridSubItems_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;

            if (e.CommandName == "delete")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());
                ContractBll bll = new ContractBll();
                bll.DeleteContractItem(ItemID);
                BindContractSubItem(string.Empty);

            }

            if (e.CommandName == "save")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());

                TextBox txtCount = e.Item.FindControl("txtCount") as TextBox; //数量
                TextBox txtPrice = e.Item.FindControl("txtPrice") as TextBox; //销售价
                //TextBox txtGuaranteeYear = e.Item.FindControl("txtGuaranteeYear") as TextBox;//保修年份
                //TextBox txtGuaranteeVendor = e.Item.FindControl("txtGuaranteeVendor") as TextBox;//厂家保修年限
                //TextBox txtRepairCost = e.Item.FindControl("txtRepairCost") as TextBox;//维修成本
                //TextBox txtLeasingRestrict = e.Item.FindControl("txtLeasingRestrict") as TextBox;//租赁年限
                //TextBox txtLeasingPrice = e.Item.FindControl("txtLeasingPrice") as TextBox;//租赁费
                //TextBox txtPromiseRevenue = e.Item.FindControl("txtPromiseRevenue") as TextBox;//承诺耗材销售额

                decimal Count = 0;
                if (txtCount.Text.Trim() != string.Empty)
                {
                    decimal.TryParse(txtCount.Text.Trim(), out Count);
                }

                decimal Price = 0;
                if (txtPrice.Text.Trim() != string.Empty)
                {
                    decimal.TryParse(txtPrice.Text.Trim(), out Price);
                }

                //int GuaranteeYear = 0;
                //if (txtGuaranteeYear.Text.Trim() != string.Empty)
                //{
                //    int.TryParse(txtGuaranteeYear.Text.Trim(), out GuaranteeYear);
                //}

                //int GuaranteeVendor = 0;
                //if (txtGuaranteeVendor.Text.Trim() != string.Empty)
                //{
                //    int.TryParse(txtGuaranteeVendor.Text.Trim(), out GuaranteeVendor);
                //}

                //decimal RepairCost = 0;
                //if (txtRepairCost.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtRepairCost.Text.Trim(), out RepairCost);
                //}

                //int LeasingRestrict = 0;
                //if (txtLeasingRestrict.Text.Trim() != string.Empty)
                //{
                //    int.TryParse(txtLeasingRestrict.Text.Trim(), out LeasingRestrict);
                //}

                //decimal LeasingPrice = 0;
                //if (txtLeasingPrice.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtLeasingPrice.Text.Trim(), out LeasingPrice);
                //}

                //decimal PromiseRevenue = 0;
                //if (txtPromiseRevenue.Text.Trim() != string.Empty)
                //{
                //    decimal.TryParse(txtPromiseRevenue.Text.Trim(), out PromiseRevenue);
                //}

                CtrtContractItemBll bll = new CtrtContractItemBll();
                CtrtContractItemEntity entity = bll.Get<CtrtContractItemEntity>(ItemID);
                entity.Count = Count;
                entity.Price = Price;
                entity.TotalPrice = Count * Price;
                //entity.GuaranteeYear = GuaranteeYear;
                //entity.GuaranteeVendor = GuaranteeVendor;
                //entity.RepairCost = RepairCost;
                //entity.LeasingRestrict = LeasingRestrict;
                //entity.LeasingPrice = LeasingPrice;
                //entity.PromiseRevenue = PromiseRevenue;

                bll.Update(entity);
                BindContractItem(string.Empty);
            }
        }

        protected void gridGuaranty_DeleteCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            Guid GuarantyID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["GuarantyID"].ToString());

            CtrtItemGuarantyBll bll = new CtrtItemGuarantyBll();
            bll.Delete(new CtrtItemGuarantyEntity(GuarantyID));
            BindGuaranty();
        }

     
        protected void gridPayment_DeleteCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid PaymentID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PaymentID"].ToString());

                CtrtContractPaymentBll bll = new CtrtContractPaymentBll();
                bll.Delete<CtrtContractPaymentEntity>(" and PaymentID = '" + PaymentID + "'");
                //BindPaymentGrid();
            }
        }

      

        private void InitContractInfo()
        {
            if (txtContractID.Value == "") return;

            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(new Guid(txtContractID.Value));
            if (entity != null)
            {
                ddlPutPaymentType.SelectedValue = entity.PutPaymentType.ToString();
                radtxtPutDiscount.Value = (double)entity.PutDiscount;
            }
        }

        protected void gridPayment_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                Guid PaymentID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PaymentID"].ToString());
                RadDatePicker txtPayDate = e.Item.FindControl("txtPayDate") as RadDatePicker;
                RadNumericTextBox txtPayAmount = e.Item.FindControl("txtPayAmount") as RadNumericTextBox;

                CtrtContractPaymentEntity entity = e.Item.DataItem as CtrtContractPaymentEntity;
                if (entity != null)
                {
                    if (entity.PayDate != DateTime.MinValue)
                        txtPayDate.SelectedDate = entity.PayDate;

                    if (entity.PayAmount != decimal.MinValue)
                        txtPayAmount.Value = (double)entity.PayAmount;
                }
            }
        }

        protected void btnSaveIncome_Click(object sender, EventArgs e)
        {
            if (txtContractID.Value == "") return;

            CtrtContractOthorIncomeExtendBll bll = new CtrtContractOthorIncomeExtendBll();
            CtrtContractOthorIncomeExtendEntity entity = bll.Get<CtrtContractOthorIncomeExtendEntity>(new Guid(txtContractID.Value));
            if (entity == null)
            {
                entity = new CtrtContractOthorIncomeExtendEntity(new Guid(txtContractID.Value));
                entity.CreatedAt = entity.LastModifiedAt = DateTime.Now;
                entity.CreatedBy = entity.LastModifiedBy = base.CurrentUserID;
            }
            entity.MachinePeriod = radtxtMachinePeriod.Value.HasValue ? (int)radtxtMachinePeriod.Value.Value : 0;
            entity.MachinePerIncome = radtxtMachinePerIncome.Value.HasValue ? (decimal)radtxtMachinePerIncome.Value.Value : 0;
            entity.MachineTotalIncome = entity.MachinePeriod * entity.MachinePerIncome;
            entity.MachineDate = raddateMachineDate.SelectedDate.HasValue ? raddateMachineDate.SelectedDate.Value : DateTime.MinValue;
            entity.MachineAlertDays = radtxtAlertDays.Value.HasValue ? (int)radtxtAlertDays.Value.Value : 0;
            entity.MachineRemark = txtMachineRemark.Text;

            entity.MaintainPeriod = radtxtMaintainPeriod.Value.HasValue ? (int)radtxtMaintainPeriod.Value.Value : 0;
            entity.MaintainPerIncome = radtxtMaintainPerIncome.Value.HasValue ? (decimal)radtxtMaintainPerIncome.Value.Value : 0;
            entity.MaintainTotalIncome = entity.MaintainPeriod * entity.MaintainPerIncome;
            entity.MaintainDate = raddateMaintainDate.SelectedDate.HasValue ? raddateMaintainDate.SelectedDate.Value : DateTime.MinValue;
            entity.MaintainAlertDays = radtxtAlertDays.Value.HasValue ? (int)radtxtAlertDays.Value.Value : 0;
            entity.MaintainRemark = txtMaintainRemark.Text;

            entity.RentPeriod = radtxtRentPeriod.Value.HasValue ? (int)radtxtRentPeriod.Value.Value : 0;
            entity.RentPerIncome = radtxtRentPerIncome.Value.HasValue ? (decimal)radtxtRentPerIncome.Value.Value : 0;
            entity.RentTotalIncome = entity.RentPeriod * entity.RentPerIncome;
            entity.RentDate = raddateRentDate.SelectedDate.HasValue ? raddateRentDate.SelectedDate.Value : DateTime.MinValue;
            entity.RentAlertDays = radtxtAlertDays.Value.HasValue ? (int)radtxtAlertDays.Value.Value : 0;
            entity.RentRemark = txtRentRemark.Text;

            bll.InsertOrUpdate(entity);
        }

        protected void gridContractItemPart_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;
            if (e.CommandName == "save")
            {
                Guid PartID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PartID"].ToString());
                RadNumericTextBox txtCount = e.Item.FindControl("txtCount") as RadNumericTextBox;

                ContractBll bll = new ContractBll();
                CtrtContractItemPartEntity entity = bll.Get<CtrtContractItemPartEntity>(PartID);
                entity.Count = txtCount.Value.HasValue ? (int)txtCount.Value.Value : 0;
                bll.Update(entity);
                //btnResreshItemPart_Click(null, null);
            }
        }

        protected void gridContractItemPart_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid PartID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PartID"].ToString());
                ContractBll bll = new ContractBll();
                bll.Delete(new CtrtContractItemPartEntity(PartID));

                //btnResreshItemPart_Click(null, null);
            }
        }

        protected void gridContractItemPart_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                if (dv != null)
                {
                    RadNumericTextBox txtCount = e.Item.FindControl("txtCount") as RadNumericTextBox;
                    txtCount.Value = Convert.ToDouble(dv["count"].ToString());
                }
            }
        }

        protected void btnResreshItemPart_Click(object sender, EventArgs e)
        {
            if (txtItemID.Value == "") return;
            ContractBll bll = new ContractBll();
            DataTable dt = bll.GetContractItemPart(new Guid(txtItemID.Value));

            //gridContractItemPart.DataSource = dt;
            //gridContractItemPart.DataBind();
        }

        protected void btnRefreshContractGift_Click(object sender, EventArgs e)
        {
            BindContractGift();
        }

        private void BindContractGift()
        {
            ContractBll bll = new ContractBll();
            gridContractGift.DataSource = bll.LoadContractGift(new Guid(txtContractID.Value));
            gridContractGift.DataBind();
        }

        protected void gridContractGift_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid GiftID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["GiftID"].ToString());
                ContractBll bll = new ContractBll();
                bll.Delete(new CtrtContractGiftEntity(GiftID));

                BindContractGift();
            }
        }

    }
}
